package com.hulk.dryad.web.control;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hulk.dryad.common.annotation.PrintlnLog;
import com.hulk.dryad.common.annotation.Idempotent;
import com.hulk.dryad.common.annotation.RespData;
import com.hulk.dryad.common.util.*;
import com.xkcoding.justauth.AuthRequestFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;



/**
 * @author lqx
 */

@Api(value = " OAuth2", tags = "社交登录")
@ApiSort(2)
@Slf4j
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OAuth2Controller {

    private final AuthRequestFactory factory;


    @ApiOperation(value = "list", notes = "授权列表")
    @GetMapping("/list")
    @RespData
    public List<String> list() {
        return factory.oauthList();
    }

    @SneakyThrows
    @ApiOperation(value = "logintype", notes = "登录")
    @ApiOperationSupport(order = 0)
	@PrintlnLog
	@Idempotent
    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) {
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }
    

	@ApiOperation(value = "callback", notes = "回调")
	@ApiOperationSupport(order = 2)
	@PrintlnLog
	@RequestMapping("/{type}/callback")
	@RespData
	public AuthResponse callback(@PathVariable String type, AuthCallback callback) {
		AuthRequest authRequest = factory.get(type);
		AuthResponse response = authRequest.login(callback);
		log.info("【response】= {}", JacksonUtil.toJson(response));
		return response;
	}


}